package com.example.koizzi.ad20180606_note;

import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class EditActivity extends AppCompatActivity {
    private EditText edId, edName;
    private TextView edAge;
    private Button btnChange;
    int totalid = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        initModule();//初始化组件
        getDataToEdit();//获取学生数据
        EditStudentData();//更改学生数据
    }
    /*获取学生数据 --start--*/
    private void getDataToEdit() {
        totalid = getIntent().getIntExtra(StudentTable.COLUMN_ID, -1);
        String name = getIntent().getStringExtra(StudentTable.COLUMN_NAME);
        int age = getIntent().getIntExtra(StudentTable.COLUMN_AGE, -1);

        edId.setText(String.valueOf(totalid));
        edName.setText(name);
        edAge.setText(String.valueOf(age));
    }
    /*获取学生数据 --end-*/

    /*更改学生数据,广播 --start--*/
    private void EditStudentData() {
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //接收EditText,uri
                Uri uri = Uri.parse(MyContentProvider.URI_STUDENT);
                int id = Integer.parseInt(edId.getText().toString());
                String name = edName.getText().toString();
                int age = Integer.parseInt(edAge.getText().toString());
                //存储数据至MyContentProvider
                ContentValues values = new ContentValues();
                values.put(StudentTable.COLUMN_ID, id);
                values.put(StudentTable.COLUMN_NAME, name);
                values.put(StudentTable.COLUMN_AGE, age);
                String where = "id=" + totalid;
                getContentResolver().update(uri, values, where, null);
                //发个广播，插入完毕
                Intent i = new Intent();
                i.setAction("CHANGE_FINISHED");
                sendBroadcast(i);
                finish();
            }
        });
    }
    /*更改学生数据,广播 --end--*/

    /*初始化组件 --start--*/
    private void initModule() {
        edId = findViewById(R.id.ed_id);
        edName = findViewById(R.id.ed_name);
        edAge = findViewById(R.id.ed_age);
        btnChange = findViewById(R.id.btn_insert);
    }
    /*初始化组件 --end--*/
}
